package nju.edu.super_scholar.xmlHelper;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class XmlImpl implements XmlInterface {

	 private Document document;
	 private Element root;
	 
	 public XmlImpl(String rootName){
		 init();
		 
		 root = this.document.createElement(rootName);
		 this.document.appendChild(root);
	 }
	 
	    public void init() {
	        try {
	            DocumentBuilderFactory factory = DocumentBuilderFactory
	                    .newInstance();
	            DocumentBuilder builder = factory.newDocumentBuilder();
	            this.document = builder.newDocument();
	        } catch (ParserConfigurationException e) {
	            System.out.println(e.getMessage());
	        }
	    }
	
	
	@Override
	public DOMSource createXml() {
		TransformerFactory tf = TransformerFactory.newInstance();
		try{
			Transformer transformer = tf.newTransformer();
            DOMSource source = new DOMSource(document);
            transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            
            return source;
		}catch (TransformerConfigurationException e) {
            System.out.println(e.getMessage());
        } catch (IllegalArgumentException e) {
            System.out.println(e.getMessage());
        }
		return null;
	}

	@Override
	public void addNodeChild(Element father, Element child) {
		father.appendChild(child);
	}

	@Override
	public Element createNode(String tag) {
		Element node = this.document.createElement(tag);
		return node;
	}

	@Override
	public void setValue(Element node, String value) {
		node.appendChild(this.document.createTextNode(value));
	}

	@Override
	public String getValue(Element element) {
		String value = element.getFirstChild().getNodeValue();
		return value;
	}
	
	public Element root(){
		return root;
	}
	
}
